package cn.car91.activity;

import java.util.ArrayList;
import java.util.List;

import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import cn.car91.R;
import cn.car91.adapter.AreaAdapter;
import cn.car91.adapter.SearchItemsAdapter;
import cn.car91.adapter.SearchItemsAdapter.SearchItemInfo;
import cn.car91.bean.Area;
import cn.car91.bean.City;
import cn.car91.bean.District;
import cn.car91.bean.Exposure;
import cn.car91.bean.Province;
import cn.car91.bean.RepairShop;
import cn.car91.http.HttpHandler;
import cn.car91.utils.Car91JsonUtil;
import cn.car91.utils.RegexUtil;
import cn.car91.view.HerilyAlertDialog;

import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;

public class ExposurePushActivity extends BaseActivity {

    @ViewInject(R.id.exposure_push_name)
    AutoCompleteTextView nameTextView;
    @ViewInject(R.id.exposure_push_phone)
    EditText phoneTextView;
    @ViewInject(R.id.exposure_push_address)
    EditText addressTextView;
    @ViewInject(R.id.exposure_push_title)
    EditText titleTextView;
    @ViewInject(R.id.exposure_push_reason)
    EditText reasonTextView;

    @ViewInject(R.id.exposure_push_area_province)
    Spinner provinceSpinner;
    @ViewInject(R.id.exposure_push_area_city)
    Spinner citySpinner;
    @ViewInject(R.id.exposure_push_area_district)
    Spinner districtSpinner;

    @ViewInject(R.id.exposure_push_submit)
    Button submitBtn;

    //VerticalScrollView scrollView;
    //MyListView listView;
    //PopupWindow popupWindow;

    AreaAdapter provinceListAdapter;
    AreaAdapter cityListAdapter;
    AreaAdapter districtListAdapter;

    SearchItemsAdapter searchAdapter;

    AreaEvent areaEvent = new AreaEvent();

    String srid = "";
    boolean canSearch = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        setContentView(R.layout.activity_exposure_push);
        super.onCreate(savedInstanceState);

        provinceListAdapter = new AreaAdapter(ExposurePushActivity.this);
        provinceSpinner.setAdapter(provinceListAdapter);
        provinceSpinner.setOnItemSelectedListener(areaEvent.onAreaItemSelectedListener);

        cityListAdapter = new AreaAdapter(ExposurePushActivity.this);
        citySpinner.setAdapter(cityListAdapter);
        citySpinner.setOnItemSelectedListener(areaEvent.onAreaItemSelectedListener);

        districtListAdapter = new AreaAdapter(ExposurePushActivity.this);
        districtSpinner.setAdapter(districtListAdapter);

        submitBtn.setOnClickListener(onSubmitClickListener);

        searchAdapter = new SearchItemsAdapter(ExposurePushActivity.this, R.layout.view_search_repairshop_item);
        reasonTextView.setOnEditorActionListener(new AutoCompleteTextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView AutoCompleteTextView, int arg1, KeyEvent arg2) {
                if (arg1 == EditorInfo.IME_ACTION_SEND || arg1 == EditorInfo.IME_ACTION_SEARCH
                        || arg1 == EditorInfo.IME_ACTION_DONE) {
                    onSubmitClickListener.onClick(submitBtn);
                    return true;
                }
                return false;
            }
        });

        nameTextView.addTextChangedListener(onSearchContentWatcher);
        nameTextView.setOnItemClickListener(onSearchItemClickListener);

        areaEvent.getArea(AreaType.province, 0);

        ((TextView) findViewById(R.id.header_text)).setText("商家举报");

        String exposure_id = getIntent().getStringExtra("eid");
        if (exposure_id != null) {
            canSearch = false;
            HttpHandler.httpHandler.getUserExposureDetail(getCar91Application().getUser().getId(), exposure_id, "null", callBackExposure);
        }
    }

    interface AreaType {
        int province = 0;
        int city = 1;
        int district = 2;
    }

    private class AreaEvent {
        int at;

        private void getArea(int areaType, int id) {
            at = areaType;

            switch (areaType) {
                case AreaType.province:
                    citySpinner.removeAllViewsInLayout();
                    districtSpinner.removeAllViewsInLayout();
                    HttpHandler.httpHandler.getAllProvinces(callBackArea);
                    break;
                case AreaType.city:
                    districtSpinner.removeAllViewsInLayout();
                    HttpHandler.httpHandler.getProvinceCities(id, callBackArea);
                    break;
                case AreaType.district:
                	HttpHandler.httpHandler.getCityDistricts(id, callBackArea);
                    break;
                default:
                    break;
            }
        }

        RequestCallBack callBackArea = new RequestCallBack() {

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                // TODO Auto-generated method stub
            }

            @Override
            public void onSuccess(ResponseInfo arg0) {
                // TODO Auto-generated method stub
                List<Area> areas = new ArrayList<Area>();
                Area area;
                switch (at) {
                    case AreaType.province:
                        List<Province> provinces = Car91JsonUtil.getDTOList(arg0.result.toString(), Province.class);
                        area = new Area();
                        area.id = 0;
                        area.name = "直辖市";
                        areas.add(area);
                        for (Province province : provinces) {
                            area = new Area();
                            area.id = province.getPid();
                            area.name = province.getName();
                            areas.add(area);
                        }
                        provinceListAdapter.setmList(areas);
                        provinceListAdapter.notifyDataSetChanged();
                        break;
                    case AreaType.city:
                        List<City> cities = Car91JsonUtil.getDTOList(arg0.result.toString(), City.class);
                        for (City city : cities) {
                            area = new Area();
                            area.id = city.getCid();
                            area.name = city.getName();
                            areas.add(area);
                        }
                        cityListAdapter.setmList(areas);
                        cityListAdapter.notifyDataSetChanged();
                        break;
                    case AreaType.district:
                        List<District> districts = Car91JsonUtil.getDTOList(arg0.result.toString(), District.class);
                        for (District district : districts) {
                            area = new Area();
                            area.id = district.getDid();
                            area.name = district.getName();
                            areas.add(area);
                        }
                        districtListAdapter.setmList(areas);
                        districtListAdapter.notifyDataSetChanged();
                        break;
                    default:
                        break;
                }
            }
        };

        OnItemSelectedListener onAreaItemSelectedListener = new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
                                       long arg3) {
                // TODO Auto-generated method stub
                TextView idTextView = (TextView) arg1.findViewById(R.id.area_id);
                int id = Integer.valueOf(idTextView.getText().toString());
                switch (arg0.getId()) {
                    case R.id.exposure_push_area_province:
                        getArea(AreaType.city, id);
                        break;
                    case R.id.exposure_push_area_city:
                        getArea(AreaType.district, id);
                        break;
                    case R.id.exposure_push_area_district:
                        break;
                    default:
                        break;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub
                if (provinceSpinner.getChildCount() == 0) {
                    areaEvent.getArea(AreaType.province, 0);
                }
            }
        };
    }

    TextWatcher onSearchContentWatcher = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
            // TODO Auto-generated method stub

        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                      int arg3) {
        }

        @Override
        public void afterTextChanged(Editable arg0) {
            // TODO Auto-generated method stub
            if (canSearch) {
                if (arg0.length() >= 2) {
                    HttpHandler.httpHandler.getSearchRepairShop(1, arg0.toString(), callBackSearch);
                }
            } else {
                canSearch = true;
                srid = "";
            }
        }

        RequestCallBack callBackSearch = new RequestCallBack() {

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onSuccess(ResponseInfo arg0) {
                // TODO Auto-generated method stub
                List<RepairShop> repairShops = Car91JsonUtil.getDTOList(arg0.result.toString(), RepairShop.class);
                List<SearchItemInfo> searchItems = new ArrayList<SearchItemInfo>();
                if (repairShops.size() > 0) {
                    for (RepairShop repairShop : repairShops) {
                        SearchItemInfo searchItemInfo = new SearchItemInfo();
                        searchItemInfo.setId(repairShop.getId());
                        searchItemInfo.setName(repairShop.getName());
                        searchItemInfo.setOther(repairShop.getDetail().getAddress());
                        searchItems.add(searchItemInfo);
                    }
                    searchAdapter.setSearchItems(searchItems);
                    nameTextView.setAdapter(searchAdapter);
                    searchAdapter.notifyDataSetChanged();
                    nameTextView.showDropDown();
                } else {
                    nameTextView.dismissDropDown();
                }
            }
        };
    };

    OnItemClickListener onSearchItemClickListener = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                long arg3) {
            // TODO Auto-generated method stub
            canSearch = false;
            //TextView idView = (TextView) arg1.findViewById(R.id.search_repairshop_id);
            TextView nameView = (TextView) arg1.findViewById(R.id.search_name);
            nameTextView.setText(RegexUtil.htmlFilter(nameView.getText().toString()));
            HttpHandler.httpHandler.getExposureRepairShop(searchAdapter.getSearchItemId((int) arg3), callBack);
        }

        private RequestCallBack callBack = new RequestCallBack() {

            @Override
            public void onFailure(HttpException arg0, String arg1) {
            }

            @Override
            public void onSuccess(ResponseInfo arg0) {
                // TODO Auto-generated method stub
                RepairShop repairShop = (RepairShop) Car91JsonUtil.getDTO(arg0.result.toString(), RepairShop.class);

                if (repairShop != null) {
                    srid = repairShop.getId();
                    City city = repairShop.getDistrict().getCity();
                    if (provinceSpinner.getChildCount() > 0) {
                        if (city.getMunicipality()) {
                            for (int i = 0; i < provinceListAdapter.getCount(); i++) {
                                Area p = (Area) provinceListAdapter.getItem(i);
                                if (p.id == 0) {
                                    provinceSpinner.setSelection(i);
                                    break;
                                }
                            }
                            for (int i = 0; i < cityListAdapter.getCount(); i++) {
                                Area c = (Area) cityListAdapter.getItem(i);
                                if (c.id == city.getCid()) {
                                    citySpinner.setSelection(i);
                                    break;
                                }
                            }
                            for (int i = 0; i < districtListAdapter.getCount(); i++) {
                                Area d = (Area) districtListAdapter.getItem(i);
                                if (d.id == repairShop.getDistrict().getDid()) {
                                    districtSpinner.setSelection(i);
                                    break;
                                }
                            }
                        } else {
                            for (int i = 0; i < provinceListAdapter.getCount(); i++) {
                                Area p = (Area) provinceListAdapter.getItem(i);
                                if (p.id == city.getProvince().getPid()) {
                                    provinceSpinner.setSelection(i);
                                    break;
                                }
                            }
                            for (int i = 0; i < cityListAdapter.getCount(); i++) {
                                Area c = (Area) cityListAdapter.getItem(i);
                                if (c.id == city.getCid()) {
                                    citySpinner.setSelection(i);
                                    break;
                                }
                            }
                            for (int i = 0; i < districtListAdapter.getCount(); i++) {
                                Area d = (Area) districtListAdapter.getItem(i);
                                if (d.id == repairShop.getDistrict().getDid()) {
                                    districtSpinner.setSelection(i);
                                    break;
                                }
                            }
                        }
                    }

                    phoneTextView.setText(repairShop.getDetail().getPhone());
                    addressTextView.setText(repairShop.getDetail().getAddress());
                }
            }
        };
    };

    OnClickListener onSubmitClickListener = new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            String name = nameTextView.getText().toString();
            long did = 0;
            try {
                did = districtSpinner.getSelectedItemId();
            } catch (Exception e) {
            }
            long cid = 0;
            try {
                cid = citySpinner.getSelectedItemId();
            } catch (Exception e) {
            }
            String phone = phoneTextView.getText().toString();
            String address = addressTextView.getText().toString();
            String title = titleTextView.getText().toString();
            String reason = reasonTextView.getText().toString();

            if (RegexUtil.isNull(name)) {
                nameTextView.requestFocus();
                nameTextView.selectAll();
            } else if (did <= 0 || cid <= 0) {
                new HerilyAlertDialog.Builder(ExposurePushActivity.this)
                        .setMessage("请选择商家所属地区")
                        .setNegativeButton("确定", null)
                        .create().show();
            } else if (RegexUtil.isNull(phone)) {
                phoneTextView.requestFocus();
                phoneTextView.selectAll();
            } else if (RegexUtil.isNull(address)) {
                addressTextView.requestFocus();
                addressTextView.selectAll();
            } else if (RegexUtil.isNull(title)) {
                titleTextView.requestFocus();
                titleTextView.selectAll();
            } else if (RegexUtil.isNull(reason)) {
                reasonTextView.requestFocus();
                reasonTextView.selectAll();
            } else {
            	HttpHandler.httpHandler.addExposure(getCar91Application().getUser().getId(), srid, name, (int)cid, (int)did, address, phone, title, reason, callBackSubmit);
            }
        }

        private RequestCallBack callBackSubmit = new RequestCallBack() {

            @Override
            public void onStart() {
                // TODO Auto-generated method stub
                submitBtn.setEnabled(false);
                super.onStart();
            }

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                // TODO Auto-generated method stub
                Toast.makeText(ExposurePushActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
                submitBtn.setEnabled(true);
            }

            @Override
            public void onSuccess(ResponseInfo arg0) {
                // TODO Auto-generated method stub
                if (arg0.result.toString().equals("1")) {
                    new HerilyAlertDialog.Builder(ExposurePushActivity.this)
                            .setMessage("举报成功，等待审核中...")
                            .setPositiveButton("完成", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface arg0, int arg1) {
                                    // TODO Auto-generated method stub
                                    finish();
                                }
                            })
                            .setNegativeButton("继续", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface arg0, int arg1) {
                                    // TODO Auto-generated method stub
                                    canSearch = false;
                                    nameTextView.setText("");
                                    phoneTextView.setText("");
                                    addressTextView.setText("");
                                    titleTextView.setText("");
                                    reasonTextView.setText("");
                                }
                            })
                            .create().show();
                } else {
                    new HerilyAlertDialog.Builder(ExposurePushActivity.this).setMessage("举报失败").create().show();
                    submitBtn.setEnabled(true);
                }
            }
        };
    };

    private RequestCallBack callBackExposure = new RequestCallBack() {

        @Override
        public void onFailure(HttpException arg0, String arg1) {
            Toast.makeText(ExposurePushActivity.this, "网络异常，请稍后再试", Toast.LENGTH_LONG).show();
        }

        @Override
        public void onSuccess(ResponseInfo arg0) {
            Exposure exposure = (Exposure) Car91JsonUtil.getDTO(arg0.result.toString(), Exposure.class);
            if (exposure != null) {
                nameTextView.setText(exposure.getName());
                phoneTextView.setText(exposure.getMobile());
                addressTextView.setText(exposure.getAddress());
                titleTextView.setText(exposure.getTitle());
                reasonTextView.setText(exposure.getReason());
            }
        }
    };
}
